package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.exception.BusinessException;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public String sendMsg(User user, HttpSession session) {
        //获取手机号
        try {
        String phone = user.getPhone();

        //生成随机的4位验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        log.info("code={}",code);
        //调用阿里云提供的短信服务API完成发送短信
        //SMSUtils.sendMessage(phone,code);
        //需要将生成的验证码保存到Session
        session.setAttribute(phone,code);

        //将生成的验证码缓存到Redis中，并且设置有效期为5分钟
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

        //回显验证码
        return code;
        }catch (Exception exception){
            log.error("发送验证码失败"+exception.getMessage());
            throw new BusinessException("发送验证码失败");
        }
    }

    @Override
    public R<String> loginout(HttpSession session) {
        //方式二（推荐使用）
        session.invalidate();
        //2.返回登录成功信息
        return R.success("登出成功了");
    }

    @Override
    public User login(String phone, String code, HttpSession session) {
        //获取session中验证码
        //Object sessionCode = session.getAttribute(phone);
        //从redis中获取缓存的验证码
        Object sessionCode = redisTemplate.opsForValue().get(phone);
        //如果session验证码不为空 对比输入验证码
        if(sessionCode == null){
            throw new BusinessException("请重新获取验证码");
        }
        if(!code.equals(code)){
            throw new BusinessException("请输入正确的验证码");
        }
        //根据手机号查询用户对象
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone,phone);

        User user = userMapper.selectOne(queryWrapper);
        //根据用户对象为空自动注册
        if(user == null){
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userMapper.insert(user);
        }
        //将用户信息存入session登录成功了
        session.setAttribute("user",user);

        //如果用户登录成功，删除Redis中缓存的验证码
        redisTemplate.delete(phone);

        return user;
    }
}
